<?php
// $Id$

/**
 */
class Controller_Admin_Product extends Controller_Abstract
{
	function actionIndex(){
		$select = Product::find();
		
		if($name = $this->_context->name){
			$select->where('product.name like ?', '%'.$name.'%');
		}
		
		if($model = $this->_context->model){
			$select->where('product.model like ?', '%'.$model.'%');
		}
		
		if($code = $this->_context->code){
			$select->where('product.code like ?', '%'.$code.'%');
		}
		
		$cid = $this->_context->category_id;
		
		if($cid && $cid != Category::rootNodeId()){
			$app = MyApp::instance();
			$cate = $app->currentCategory();
			
			$select = Product::findInCateIds($cate->subcateIdsAndSelfId(), $select);
		}
		
		$page = $this->_context->page ? $this->_context->page : 1;
		$select->limitPage($page);
		$pagination = $select->getPagination();
		
		$this->_view['products'] = $select->getAll();
		$this->_view['pagination'] = $pagination;
		
	}
	
	function actionEdit(){
		$pid = $this->_context->pid;
		$p = Product::find('product_id=?',$pid)->getOne();
		if($p->id()){
			$this->_view['pageTitle'] = '产品资料编辑';
		}else{
			$this->_view['pageTitle'] = '新增产品';
		}
		
		$this->_view['product'] = $p;
	}
	
	function actionCopy(){
		$pid = $this->_context->pid;
		$p = Product::find('product_id=?',$pid)->getOne();
		$p->hot = 0;
		$this->_view['product'] = $p;
		$this->_view['copyMode'] = true;
		$this->_view['pageTitle'] = '复制产品';
		$this->_forward('/edit');
	}
	
	function actionSave(){
		$pid = $this->_context->product_id;
		
		$p = Product::find('product_id=?',$pid)->forUpdate()->getOne();
		$p->changeProps($_POST);
		$p->save();
		
		if(isset($this->_context->dataType) && $this->_context->dataType == 'json'){
			$ret = array(
  			'ack' => 'success',
   		);
   		return json_encode($ret);
   		
		}else{
			$url = url('/edit',array('pid'=>$p->id()));
			return $this->_redirect($url);
		}
	}
	
	function actionRemove(){
		$pid = $this->_context->product_id;
		
		$p = Product::find('product_id=?',$pid)->getOne();
		
		try{
			$p->destroy();
			$ret = array(
  			'ack' => 'success',
   		);
   		
		}catch(Exception $e){
			$ret = array(
 				'ack' => 'error',
 				'errorMsg' => $e->getMessage(),
 			);
		}
		
		return json_encode($ret);
	}
	
	function actionResort(){
 		$ids = Q::normalize($this->_context->ids);
 		
 		foreach($ids as $i => $id){
 			$p = Product::find('product_id=?',$id)->getOne();
 			if($p->id()){
 				$p->sort = $i;
 				$p->save();
 			}
 		}
 		
 		$ret = array(
			'ack' => 'success',
 		);
 		return json_encode($ret);
 	}
}